package meihua.stopcarapp.ui;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import meihua.mylibrary.base.BaseActivity;
import meihua.stopcarapp.R;
import meihua.stopcarapp.utils.ToastUtil;
import meihua.stopcarapp.utils.UIUtils;
import meihua.stopcarapp.widget.dialog.SelectPicDialog;

import static meihua.stopcarapp.R.id.toolbar_left;

/**
 * 报修
 */

public class RepairActivity extends BaseActivity {
    @Bind(toolbar_left)
    ImageView toolbarLeft;
    @Bind(R.id.toolbar_center)
    TextView toolbarCenter;
    @Bind(R.id.toolbar_right)
    ImageView toolbarRight;
    @Bind(R.id.toolbar)
    RelativeLayout toolbar;
    @Bind(R.id.repair_break_lock_txt)
    TextView mBreakLockTxt;
    @Bind(R.id.repair_break_car_txt)
    TextView mBreakCarTxt;
    @Bind(R.id.repair_break_llegal_txt)
    TextView mBreakLlegalTxt;
    @Bind(R.id.repair_break_other_txt)
    TextView mBreakOtherTxt;
    @Bind(R.id.repair_carno_et)
    EditText mCarnoEt;
    @Bind(R.id.repair_beizhu_et)
    EditText mBeizhuEt;
    @Bind(R.id.repair_sumbit_txt)
    TextView mSumbitTxt;
    @Bind(R.id.activity_repair_photo_add)
    ImageView activityRepairPhotoAdd;
    @Bind(R.id.activity_repair_image_layout)
    LinearLayout activityRepairImageLayout;

    private Bitmap bitmap;
    private TextView selectPicTvCamera;
    private TextView selectPicTvPic;
    private BreakStatusTextView lockTxt;//私锁乱用
    private BreakStatusTextView carTxt;//车位损坏
    private BreakStatusTextView llegalTxt;//违规乱停
    private BreakStatusTextView otherTxt;//其他
    private SelectPicDialog dialog;
    int image_size = 0;
    /* 周围环境图片名字 */
    private static final String PHOTO_FILE_NAME = "repair_photo.jpg";
    private static final String IMAGE_UNSPECIFIED = "image/*"; //所有圖片
    private File mPhotoFile;
    private String mPhotoPath;
    private File repairFile1 = null;
    private File repairFile2 = null;
    private File repairFile3 = null;

    private static final int PHOTO_REQUEST_CAREMA = 1;
    private static final int PHOTO_REQUEST_GALLERY = 2;
    private static final int PHOTO_REQUEST_CUT = 3;

    @Override
    public int getLayoutId() {
        return R.layout.activity_repair;
    }

    /**
     * 入口
     *
     * @param activity
     */
    public static void startAction(Activity activity) {
        Intent intent = new Intent(activity, RepairActivity.class);
        activity.startActivity(intent);
    }

    @Override
    public void initPresenter() {

    }

    @Override
    public void initView(Bundle savedInstanceState) {
        toolbarCenter.setText("报修");
        toolbarRight.setVisibility(View.INVISIBLE);
        lockTxt = new BreakStatusTextView(false, mBreakLockTxt);
        carTxt = new BreakStatusTextView(false, mBreakCarTxt);
        llegalTxt = new BreakStatusTextView(false, mBreakLlegalTxt);
        otherTxt = new BreakStatusTextView(false, mBreakOtherTxt);
        toolbarLeft.setImageResource(R.mipmap.ic_back);
        dialog = new SelectPicDialog(this, R.style.simple_dialog) {

            @Override
            public int getLayoutId() {
                return R.layout.dialog_selectpic_layout;
            }

            @Override
            public void initDialog(View view) {
                selectPicTvCamera = (TextView) view.findViewById(R.id.dialog_select_camera_txt);
                selectPicTvPic = (TextView) view.findViewById(R.id.dialog_select_pic_txt);
                selectPicTvCamera.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent;
                        intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//开始拍照
                        mPhotoPath = getSDPath() + "/" + getPhotoFileName();
                        mPhotoFile = new File(mPhotoPath);
                        if (mPhotoFile.exists()) {
                            mPhotoFile.delete();//创建新文件
                        }
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mPhotoFile));//Intent有了图片的信息
                        startActivityForResult(intent, PHOTO_REQUEST_CAREMA);//跳转界面传回拍照所得数据
                    }
                });
                selectPicTvPic.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // 激活系统图库，选择一张图片
                        Intent intent = new Intent(Intent.ACTION_PICK, null);
                        //从所有图片中进行选择
                        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_UNSPECIFIED);
                        startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
                    }
                });
                view.findViewById(R.id.dialog_select_cancle_txt).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
            }
        };
    }

    public String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState()
                .equals(android.os.Environment.MEDIA_MOUNTED);   //判断sd卡是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();//获取跟目录
        }
        return sdDir.toString();
    }

    private String getPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat("'IMG'_yyyyMMdd_HHmmss");
        return dateFormat.format(date) + ".jpg";
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        dialog.dismiss();
        switch (requestCode) {
            case PHOTO_REQUEST_GALLERY:    //相册
                if (data == null) return;
                try {
                    Uri selectedImage = data.getData(); //获取系统返回的照片的Uri
                    String[] filePathColumn = {MediaStore.Images.Media.DATA};
                    Cursor cursor = getContentResolver().query(selectedImage,
                            filePathColumn, null, null, null);//从系统表中查询指定Uri对应的照片
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    String picturePath = cursor.getString(columnIndex);  //获取照片路径
                    cursor.close();
                    bitmap = compressBitmap(picturePath);
                    showImage(bitmap);
                } catch (Exception e) {
                    // TODO Auto-generatedcatch block
                    e.printStackTrace();
                }
                break;
            case PHOTO_REQUEST_CAREMA:
                Bitmap bitmap = null;
                try {
                    bitmap = compressBitmap(mPhotoFile.getAbsolutePath());
                } catch (Exception e) {
                    Toast.makeText(this, "memery problems", Toast.LENGTH_LONG).show();
                }
                if (bitmap != null) {
                    showImage(bitmap);
                }
                break;
            default:
                break;
        }
    }

    /**
     * 获取图片的旋转角度，有些系统把拍照的图片旋转了，有的没有旋转
     * 将图片压缩并返回
     * @param bitmapFilePath
     * @return
     */
    public Bitmap compressBitmap(String bitmapFilePath){
        int degree = readPictureDegree(bitmapFilePath);
        //bitmap工厂
        BitmapFactory.Options options = new BitmapFactory.Options();
        // 先设置为TRUE不加载到内存中，但可以得到宽和高
        options.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(bitmapFilePath, options); // 此时返回bitmap为空
        options.inSampleSize = computeSampleSize(options, -1, 128*128);//对照片进行压缩
        options.inJustDecodeBounds = false;
        /**
        * 把图片旋转为正的方向
        */
        return rotaingImageView(degree, BitmapFactory.decodeFile(bitmapFilePath, options));
    }
    /**
     * 读取图片属性：旋转的角度
     * @param path 图片绝对路径
     * @return degree旋转的角度
     */
    public static int readPictureDegree(String path) {
        int degree  = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }
    /*
        * 旋转图片
        * @param angle
        * @param bitmap
        * @return Bitmap
        */
    public static Bitmap rotaingImageView(int angle , Bitmap bitmap) {
        //旋转图片 动作
        Matrix matrix = new Matrix();;
        matrix.postRotate(angle);
        System.out.println("angle2=" + angle);
        // 创建新的图片
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
                bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        return resizedBitmap;
    }
    /**
     *  计算压缩比例
     * @param options
     * @param minSideLength
     * @param maxNumOfPixels
     * @return
     */
    public static int computeSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) {
        int initialSize = computeInitialSampleSize(options, minSideLength, maxNumOfPixels);
        int roundedSize;
        if (initialSize <= 8) {
            roundedSize = 1;
            while (roundedSize < initialSize) {
                roundedSize <<= 1;
            }
        } else {
            roundedSize = (initialSize + 7) / 8 * 8;
        }
        return roundedSize;
    }

    /**
     * 计算照片最初大小
     * @param options
     * @param minSideLength
     * @param maxNumOfPixels
     * @return
     */
    private static int computeInitialSampleSize(BitmapFactory.Options options,int minSideLength, int maxNumOfPixels) {
        double w = options.outWidth;
        double h = options.outHeight;
        int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));
        int upperBound = (minSideLength == -1) ? 128 :(int) Math.min(Math.floor(w / minSideLength), Math.floor(h / minSideLength));
        if (upperBound < lowerBound) {
            // return the larger one when there is no overlapping zone.
            return lowerBound;
        }
        if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
            return 1;
        } else if (minSideLength == -1) {
            return lowerBound;
        } else {
            return upperBound;
        }
    }

    //显示照片
    void showImage(Bitmap bitmap) {
//        repairPhotoAdd.setImageBitmap(bitmap);
        final View view = UIUtils.inflate(R.layout.view_repair_image);
        ImageView iv_image = (ImageView) view.findViewById(R.id.view_repair_photo_add);
        iv_image.setImageBitmap(bitmap);
        ImageView iv_delete = (ImageView) view.findViewById(R.id.view_repair_photo_delete1);
        iv_delete.setVisibility(View.VISIBLE);
        iv_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                image_size--;
                activityRepairImageLayout.removeView(view);
                if (image_size < 3) {
                    activityRepairPhotoAdd.setVisibility(View.VISIBLE);
                }
            }
        });
        activityRepairImageLayout.addView(view);
        image_size++;
        if (image_size >= 3) {
            activityRepairPhotoAdd.setVisibility(View.GONE);
        }

    }

    @OnClick({R.id.repair_break_lock_txt, R.id.repair_break_car_txt, R.id.repair_break_llegal_txt,
            R.id.repair_break_other_txt, R.id.repair_sumbit_txt, R.id.toolbar_left, R.id.activity_repair_photo_add})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.toolbar_left:
                finish();
                break;
            case R.id.activity_repair_photo_add:
                dialog.show();
                break;
            case R.id.repair_break_lock_txt:
                lockTxt.toggle();
                break;
            case R.id.repair_break_car_txt:
                carTxt.toggle();
                break;
            case R.id.repair_break_llegal_txt:
                llegalTxt.toggle();
                break;
            case R.id.repair_break_other_txt:
                otherTxt.toggle();
                break;
            case R.id.repair_sumbit_txt:
                ToastUtil.showShort(this,activityRepairImageLayout.getChildCount()+"");
                if (TextUtils.isEmpty(getBreak())) {
                    ToastUtil.showShort(RepairActivity.this, "请选择故障类型");
                } else if (activityRepairImageLayout.getChildCount()<1){
                    ToastUtil.showShort(RepairActivity.this, "请添加至少一张周边环境图片");
                } else {
                    ToastUtil.showShort(RepairActivity.this, getBreak());
                    for (int i = 0; i < activityRepairImageLayout.getChildCount(); i++) {

                    }
                }
                break;
        }
    }

    //获取选中的故障类型
    public String getBreak() {
        StringBuilder builder = new StringBuilder();
        if (lockTxt.isChecked) {
            builder.append(lockTxt.content.getText().toString()).append("-");
        }
        if (carTxt.isChecked) {
            builder.append(carTxt.content.getText().toString()).append("-");
        }
        if (llegalTxt.isChecked) {
            builder.append(lockTxt.content.getText().toString()).append("-");
        }
        if (otherTxt.isChecked) {
            builder.append(otherTxt.content.getText().toString()).append("-");
        }
        if (builder.length() <= 0) {
            return "";
        } else {
            return builder.deleteCharAt(builder.length() - 1).toString();
        }


    }

    public class BreakStatusTextView {

        public boolean isChecked;
        public TextView content;

        public BreakStatusTextView(boolean isChecked, TextView content) {
            this.isChecked = isChecked;
            this.content = content;
        }

        public void toggle() {
            if (isChecked) {//如果是选中状态 就改成未选中状态
                isChecked = false;
                content.setBackgroundResource(R.drawable.corner_black_bg);
                content.setTextColor(ContextCompat.getColor(RepairActivity.this, R.color.color_363332));
            } else {//如果是未选中状态 就改成选中状态
                isChecked = true;
                content.setBackgroundResource(R.drawable.corner_black_solid_bg);
                content.setTextColor(ContextCompat.getColor(RepairActivity.this, R.color.white));
            }

        }
    }


}
